package com.mceil.mylibrary.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;


import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.mceil.mylibrary.annotation.ContentView;
import com.mceil.mylibrary.annotation.ViewInject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public abstract class BaseActivity extends AppCompatActivity {
    //每页数量
    protected int pageSize = 10;
    //页码
    protected int pageIndex = 0;
    //token
    protected String token;
    //userId
    protected String userId;

    protected Context mContext;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        injectContentView(this);
        injectView(this);

        mContext = this;
        initPreferences();
        initView();
        initData();
    }

    //加载缓存信息
    protected abstract void initPreferences();


    //初始化视图
    protected abstract void initView();

    //初始化数据
    protected abstract void initData();


    private void injectContentView(Activity activity) {
        //获取activity的类实例
        Class<? extends Activity> clazz = activity.getClass();
        //获取到activity的ContentView注解
        ContentView contentView = clazz.getAnnotation(ContentView.class);
        if (contentView != null) {
            //如果activity上面存在这个注解的话，就取出这个注解对应的value值，就是前面设置的布局
            int layoutId = contentView.value();
            try {
                //利用反射调用setContentView方法，完成注入
                Method setViewMethod = clazz.getMethod("setContentView", int.class);
                setViewMethod.invoke(activity, layoutId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void injectView(Activity activity) {
        //获取activity的类实例
        Class<? extends Activity> clazz = activity.getClass();
        //获取activity的所有成员变量
        Field[] fields = clazz.getDeclaredFields();
        //遍历成员变量，获取成员变量上的ViewInject注解
        for (Field field : fields) {
            //获取字段上面的注解对象，同有则继续下一个字段
            ViewInject viewInject = field.getAnnotation(ViewInject.class);
            if (viewInject != null) {
                //获取ViewInject注解的View的id
                int viewId = viewInject.value();
                //获取控件
                View view = activity.findViewById(viewId);
                try {
                    //设置field为可访问，就算私有的也能访问到，能够提高效率
                    field.setAccessible(true);
                    //将该控件设置给field对象
                    field.set(activity, view);//将activity对象的view控件设置给属性对应上面的例子是mEditText=findViewById(viewId)
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
